import { defineStore } from 'pinia'
import { ArticleService } from '@/api/services/articleService'
import type { ArticleVO, AttitudeVO } from '@/types/article'
import zm from '@/utils/zm'

/**
 * 文章展示专用Store
 * 职责：管理文章列表、文章详情展示、用户交互（点赞、收藏等）
 */
export const useArticleStore = defineStore('article', {
  state() {
    return {
      // 文章列表相关
      articleList: [] as ArticleVO[],
      loading: false,
      hasMore: true,
      currentPage: 1,
      
      // 当前查看的文章
      currentArticle: {} as ArticleVO,
      articleHtml: '', // 文章HTML内容
      
      // 用户交互状态
      likeCount: 0,
      isLiked: false,
      isDisliked: false,
      isCollected: false,
      
      // 文章评论相关
      comments: [] as any[],
      commentCount: 0
    }
  },
  
  actions: {
    /**
     * 刷新文章列表
     */
    async refreshArticleList() {
      this.loading = true
      try {
        const data = await ArticleService.getArticleList()
        this.articleList = data
      } catch (error) {
        zm.error('获取文章列表失败')
        console.error('Refresh article list error:', error)
      } finally {
        this.loading = false
      }
    },

    /**
     * 加载更多文章
     */
    async loadMoreArticles() {
      if (this.loading || !this.hasMore) return
      
      this.loading = true
      try {
        // TODO: 实现分页加载逻辑
        this.currentPage += 1
        // const newArticles = await ArticleService.getArticleList(this.currentPage)
        // this.articleList = [...this.articleList, ...newArticles]
      } catch (error) {
        zm.error('加载更多文章失败')
      } finally {
        this.loading = false
      }
    },

    /**
     * 查询文章详情（用于展示）
     */
    async queryArticleDetail(articleId: string) {
      try {
        const data = await ArticleService.getArticleById(articleId, true)
        
        if (zm.isNotNon(data)) {
          // 设置文章基本信息
          this.currentArticle = data.article || data
          
          // 设置文章HTML内容
          if (zm.isNotNon(data.content)) {
            this.articleHtml = data.content.html || data.content
            this.likeCount = this.currentArticle.agreeNum || 0
          }
          
          // 重置用户交互状态
          this.resetUserInteractionState()
          
          // 设置用户态度状态
          if (zm.isNotNon(data.attitude) && Array.isArray(data.attitude)) {
            data.attitude.forEach((attitude: AttitudeVO) => {
              switch (attitude.type) {
                case 'agree':
                  this.isLiked = true
                  break
                case 'dislike':
                  this.isDisliked = true
                  break
                case 'collect':
                  this.isCollected = true
                  break
              }
            })
          }
        }
      } catch (error) {
        zm.error('获取文章详情失败')
        console.error('Query article detail error:', error)
      }
    },

    /**
     * 查询文章详情（不包含用户态度）
     */
    async queryArticleWithoutAttitude(articleId: string) {
      try {
        const data = await ArticleService.getArticleById(articleId, false)
        if (zm.isNotNon(data)) {
          this.currentArticle = data.article || data
          this.articleHtml = data.content?.html || data.content || ''
          this.likeCount = this.currentArticle.agreeNum || 0
          this.resetUserInteractionState()
        }
      } catch (error) {
        zm.error('获取文章内容失败')
        console.error('Query article without attitude error:', error)
      }
    },

    /**
     * 展示用户对文章的态度
     */
    async showAttitude(attitudeData: AttitudeVO) {
      try {
        await ArticleService.showAttitude(attitudeData)
        
        // 根据操作类型显示不同的提示信息
        const messages = {
          agree: '点赞成功~',
          noAgree: '取消点赞成功~',
          dislike: '点踩成功~',
          collect: '收藏成功~',
          noCollect: '取消收藏成功~',
          afterDislike: '操作成功~'
        }
        
        const message = messages[attitudeData.type as keyof typeof messages] || '操作成功~'
        zm.success(message)
        
      } catch (error) {
        zm.error('操作失败，请重试')
        console.error('Show attitude error:', error)
      }
    },

    /**
     * 设置当前文章（从列表选择）
     */
    setCurrentArticle(article: ArticleVO) {
      this.currentArticle = article
      this.resetUserInteractionState()
    },

    /**
     * 重置用户交互状态
     */
    resetUserInteractionState() {
      this.isLiked = false
      this.isDisliked = false
      this.isCollected = false
      this.likeCount = this.currentArticle.agreeNum || 0
    },

    /**
     * 搜索文章
     */
    async searchArticles(keyword: string, filters?: any) {
      this.loading = true
      try {
        const results = await ArticleService.searchArticles(keyword, filters)
        this.articleList = results
      } catch (error) {
        zm.error('搜索失败')
        console.error('Search articles error:', error)
      } finally {
        this.loading = false
      }
    }
  },
  
  getters: {
    /**
     * 是否有文章数据
     */
    hasArticles(): boolean {
      return this.articleList.length > 0
    },

    /**
     * 当前文章是否有内容
     */
    hasCurrentArticle(): boolean {
      return zm.isNotNon(this.currentArticle.id)
    },

    /**
     * 格式化的文章创建时间
     */
    formattedCreateTime(): string {
      if (!this.currentArticle.createTime) return ''
      return new Date(this.currentArticle.createTime).toLocaleDateString()
    }
  }
})
